from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404, redirect
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.core import paginator

from tickets.models import Ticket, Note
from tickets.forms import TicketsOwnedForm, CreateTicketForm, UserAddNoteForm, WorkerAddNoteForm
from tickets.lib import send_email


def user_portal(request):
	# generate portal for user to create ticket or list tickets
	form = TicketsOwnedForm()
	return render_to_response('user_portal.html', {
									'form': form 
								}, context_instance=RequestContext(request) )


def ticket_list(request, t_status=None):
	if request.method == 'POST':
		# process the email address and find tickets owned by the user
		form = TicketsOwnedForm(request.POST)
		if form.is_valid():
			# get form submitter
			submitter = request.POST['submitter_email']
			if t_status is None:
				# search the db and return projects owned by submitter, excluding resolved and closed
				tickets_owned = get_list_or_404(Ticket, submitter_email__iexact=submitter, status__in=[1, 2, 5])
			else:
				# search the db and return projects owned by submitter and belonging to a status
				tickets_owned = get_list_or_404(Ticket, submitter_email__iexact=submitter, status=t_status)
			return render_to_response('ticket_list.html', {
											'tickets': tickets_owned,
											'submitter_email': submitter
										}, context_instance=RequestContext(request) )
		else: 
			# redirect back to the template with an error (no email address submitted)
			return render_to_response('user_portal.html', {
											'form': form,
										}, context_instance=RequestContext(request) )
	else:
		# display all tickets, excluding resolved and closed
		if t_status is None:
			tickets_owned = get_list_or_404(Ticket, status__in=[1, 2, 5])
		else:
			tickets_owned = get_list_or_404(Ticket, status=t_status)
		return render_to_response('ticket_list.html', {
										'tickets': tickets_owned
									}, context_instance=RequestContext(request) )

def ticket_detail(request, ticket_id):
	# return ticket details (not for editing, but does allow notes)
	# notes should only have the comment field and email field available
	t = get_object_or_404(Ticket, pk=ticket_id)
	# generate a form for a new note on this ticket
	f = UserAddNoteForm()
	return render_to_response('user_ticket_detail.html', {
									'ticket': t,
									'form': f
								}, context_instance=RequestContext(request) )

def add_note(request, ticket_id):
	# add note to a ticket (users only, requires an email address)
	t = Ticket.objects.get(pk=ticket_id)
	if request.method == 'POST':
		new_note = Note(ticket=t)
		f = UserAddNoteForm(request.POST, instance=new_note)
		if f.is_valid():
			f.save()
			# send an email notifying everyone involved
			to_addresses = t.email_to_list()
			to_addresses.append('it@missoulaboneandjoint.com')
			subject = 'Note Added'
			location = request.build_absolute_uri(reverse('public_ticket_detail', args=(t.id,)))
			content = {	'header': 'Note Added', 
						'body': 'A note has been added to {ticket_name}.\nView it at <a href="{location}">{location}</a>'.format(
							location = location,
							ticket_name = t.title,
						),
			}
			send_email(to_addresses, 'it@missoulaboneandjoint.com', subject, content)
			return redirect(reverse('public_ticket_detail', args=(t.id,)))
	else:
		# generate a new note form
		f = UserAddNoteForm()

	# get our ticket info for display
	return render_to_response('user_ticket_detail.html', {
									'ticket': t,
									'form': f
								}, context_instance=RequestContext(request) )

		
def ticket_create(request):
	# create a new ticket and open the ticket
	if request.method == 'POST':
		form = CreateTicketForm(request.POST)
		if form.is_valid():
			# get form submitter
			submitter = request.POST['submitter_email']
			# add ticket to db
			t = form.save()
			# send an email notifying everyone involved
			to_addresses = t.email_to_list()
			to_addresses.append('it@missoulaboneandjoint.com')
			subject = 'New Ticket'
			location = request.build_absolute_uri(reverse('public_ticket_detail', args=(t.id,)))
			content = {	'header': 'New Ticket',
						'body': 'A new ticket has been created.\nView it at <a href="{location}">{location}</a>'.format(
							location = location,
							ticket_name = t.title,
						),
			}
			send_email(to_addresses, 'it@missoulaboneandjoint.com', subject, content)
			# open the ticket for them
			return redirect(reverse('public_ticket_detail', args=(t.id,)))
	else:
		form = CreateTicketForm()

	return render_to_response('create_ticket.html', {
									'form': form 
								}, context_instance=RequestContext(request) )


def ticket_re_open(request, ticket_id):
	# re-open a ticket for a user
	t = get_object_or_404(Ticket, pk=ticket_id)
	if request.method == 'POST':
		n = Note(ticket=t, action=5)
		f = UserAddNoteForm(request.POST, instance=n)
		if f.is_valid():
			t.status = 1
			# raise the priority if it isn't already critical
			if t.priority <= 4:
				t.priority += 1
			t.save()
			f.save()
			# send an email notifying everyone involved
			to_addresses = t.email_to_list()
			to_addresses.append('it@missoulaboneandjoint.com')
			subject = 'Ticket Re-Opened'
			location = request.build_absolute_uri(reverse('public_ticket_detail', args=(t.id,)))
			content = {	'header': 'New Ticket',
						'body': 'The ticket "{ticket_name}" has been re-opened.\nView it at <a href="{location}">{location}</a>'.format(
							location = location,
							ticket_name = t.title,
						),
			}
			send_email(to_addresses, 'it@missoulaboneandjoint.com', subject, content)
			return redirect(reverse('public_ticket_detail', args=(t.id,)))

	# generate a form to add a note to notify of the ticket status change
	n = Note(ticket=t)
	f = UserAddNoteForm(instance=n)
	return render_to_response('user_re_open_ticket.html', {
								'ticket': t,
								'form': f,
								}, context_instance=RequestContext(request) )
